import { defineStore } from 'pinia'
import { ref } from 'vue'
import { addCartApi, deleteCartApi } from '@/apis/cart'
import { useUserStore } from '../store'

export type CartListType = {
  id: string
  name: string
  picture: string
  price: string
  count: number
  skuId: string
  attrsText: string
  selected: boolean
}

export const useCartListStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()
    // 购物车数据类型
    const cartList = ref<CartListType[]>([])
    // 表格选中数据列表
    const multipleSelection = ref<CartListType[]>([])
    // 从本地获取购物车商品
    const getCartList = () => {
      cartList.value = JSON.parse(localStorage.getItem('cartList') || '[]') || []
      multipleSelection.value = JSON.parse(localStorage.getItem('payCartList') || '[]')
    }
    getCartList()

    // 清空本地购物车数据
    const clearLocalCart = () => {
      localStorage.removeItem('cartList')
      getCartList()
    }
    // 加入购物车
    const addCart = async (goods: CartListType) => {
      if (userStore.token !== '') {
        await addCartApi(goods)
        return
      }

      // 判断购物车是否有商品
      if (cartList.value.length !== 0) {
        // 有商品
        // 判断购物车中是否有此商品
        const isGoods = cartList.value?.find((item) => item.id === goods.id)
        if (isGoods) {
          // 有此商品
          cartList.value.map((item) => {
            if (item.id === isGoods.id) {
              item.count += goods.count
            }
          })
        } else {
          // 购物车没有此商品
          cartList.value.push(goods)
        }
      } else {
        // 购物车没有商品
        cartList.value?.push(goods)
      }
      // 本地保存没有登录时添加的商品
      localStorage.setItem('cartList', JSON.stringify(cartList.value))
    }

    // 删除购物车商品-登录时
    const deleteCart = async (ids: string[]) => {
      await deleteCartApi(ids)
    }

    // 删除本地购物车商品
    const deleteLocalCart = (id: string) => {
      // 删除cartList数据
      const cartId = cartList.value.findIndex((item) => item.id === id)
      cartList.value.splice(cartId, 1)
      // 改变本地购物车数据
      localStorage.setItem('cartList', JSON.stringify(cartList.value))
    }

    // 添加要去支付的购物车数据
    const addPayCartList = (data: CartListType[]) => {
      multipleSelection.value = data
      // 本地保存
      localStorage.setItem('payCartList', JSON.stringify(multipleSelection.value))
    }

    // 清空要求支付的购物车数据
    const clearPayCartList = () => {
      multipleSelection.value = []
      // 从本地保存中删除
      localStorage.removeItem('payCartList')
    }

    return {
      cartList,
      multipleSelection,
      clearLocalCart,
      addCart,
      deleteLocalCart,
      deleteCart,
      addPayCartList,
      clearPayCartList,
    }
  },
  {
    persist: true,
  },
)
